<template>
  <div v-for="(item, i) in items" :key="i" class="relative">
    <transition
      mode="out-in"
      enter-active-class="animate__animated animate__fadeIn"
      leave-active-class="animate__animated animate__fadeOut"
    >
      <div v-if="currentIndex == i" class="absolute inset-0">
        <slot :item="item"></slot>
      </div>
    </transition>
  </div>
</template>
<script lang="ts">
import { ref, defineComponent, onMounted, toRefs, PropType, Prop } from "vue";

export default defineComponent({
  props: {
    autoSlide: {
      type: Boolean,
      default: true,
    },
    items: {
      type: Array as PropType<Array<any>>, // todo just can pass ts, but not perfect
      required: true,
    },
  },
  setup(props) {
    const { autoSlide, items } = toRefs(props);
    const currentIndex = ref(0);

    const len = items.value.length;

    const nextHandler = () => {
      if (currentIndex.value < len - 1) {
        currentIndex.value++;
      }
    };

    const preHandler = () => {
      if (currentIndex.value > 0) {
        currentIndex.value--;
      }
    };

    onMounted(() => {
      // 定时轮播
      if (autoSlide.value) {
        setInterval(() => {
          if (currentIndex.value < len - 1) {
            currentIndex.value++;
          } else {
            currentIndex.value = 0;
          }
        }, 6000);
      }
    });
    return {
      items,
      nextHandler,
      preHandler,
      currentIndex,
    };
  },
});
</script>
